﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.BaseQueryModel;
using ZBJF.Warranty.Model.ViewModel.PageActionManager;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Areas.System.Controllers
{
    public class AdminController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult Index(SystemUserModel model)
        {
            int rowCount = 0;
            var result = ServiceFactory.SystemUserServiceInstance.GetPagingList(model, out rowCount).Include(o => o.RoleToSystemUser).Include(o => o.InsuranceCompany).ToList().Select(o =>
            {
                return new
                {
                    o.ID,
                    o.UserAccount,
                    o.UserDisPlayName,
                    o.IsAvailable,
                    o.CreateBy,
                    CreateTime = o.CreateTime.ToString("yyyy-M-d H:m:s"),
                    CompanyName = o.InsuranceCompanyID.HasValue ? o.InsuranceCompany.CompanyName : "",
                    ParentCompanyName = o.InsuranceCompanyID.HasValue ? o.InsuranceCompany.ParentCompanyName : "",
                    BelongApplicationType =
                        EnumHelper.Instance.GetDescription(typeof(ApplicationType), o.BelongApplicationType),
                    RoleNames =
                        o.RoleToSystemUser.Where(r => r.SystemUser.ID == o.ID)
                            .Select(r => r.SystemRole.RoleName)
                            .ToList()
                            .Aggregate(string.Empty, (c, d) => c + d + ",").Trim(',')
                };
            });

            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = rowCount,
                iTotalDisplayRecords = rowCount,
                aaData = result
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Edit(long id)
        {
            var result = ServiceFactory.SystemUserServiceInstance.Load(id);
            return View(result);
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Save(Model.SystemUser model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };
            if (ModelState.IsValid)
            {
                if (model.ID > 0)
                {
                    if (ServiceFactory.SystemUserServiceInstance.IsExist(model.UserAccount, (ApplicationType)model.BelongApplicationType, model.ID))
                    {
                        responseResult.Message = "已存在相同的账号";
                    }
                    else
                    {
                        var systemUser = ServiceFactory.SystemUserServiceInstance.Load(model.ID);
                        if (systemUser != null)
                        {
                            systemUser.IsAvailable = model.IsAvailable;
                            systemUser.UserDisPlayName = model.UserDisPlayName;
                            systemUser.UserAccount = model.UserAccount;
                            systemUser.UserPhone = model.UserPhone;
                            systemUser.BelongApplicationType = model.BelongApplicationType;
                            systemUser.UserType = model.UserType;
                            if (model.UserType == (byte)UserType.InsuranceCompanyUser)
                            {
                                systemUser.InsuranceCompanyID = model.InsuranceCompanyID;
                                systemUser.ServiceProviderID = null;
                            }
                            else if (model.UserType == (byte)UserType.ServiceProviderUser)
                            {
                                systemUser.InsuranceCompanyID = null;
                                systemUser.ServiceProviderID = model.ServiceProviderID;
                            }
                            responseResult.Success = ServiceFactory.SystemUserServiceInstance.UpdateEntities(systemUser);
                        }
                        else
                        {
                            responseResult.Message = "信息有误，请刷新页面后重试！";
                        }
                    }
                }
                else
                {
                    if (!ServiceFactory.SystemUserServiceInstance.IsExist(model.UserAccount, (ApplicationType)model.BelongApplicationType))
                    {
                        model.Password = CommonMethod.JiaMi(model.Password);
                        model.CreateBy = CurrentUser != null ? CurrentUser.UserAccount : "admin";
                        model.CreateTime = DateTime.Now;
                        responseResult.Success = ServiceFactory.SystemUserServiceInstance.AddEntities(model).ID > 0;
                    }
                    else
                    {
                        responseResult.Message = "该用户已存在";
                    }
                }
            }
            else
            {
                responseResult.Message = "信息不完整";
            }
            TempData["responseResult"] = responseResult;
            return RedirectToAction("Edit", new { id = model.ID });
        }

        /// <summary>
        /// 更改用户可用状态
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="isAvailable">用户状态</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id = 0, bool isAvailable = false)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var result = ServiceFactory.SystemUserServiceInstance.Load(id);
            if (result != null)
            {
                result.IsAvailable = isAvailable;
                responseResult.Success = ServiceFactory.SystemUserServiceInstance.UpdateEntities(result);
            }
            else
            {
                responseResult.Message = "找不到该用户";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        #region 修改密码
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="id">用户Id</param>
        /// <param name="newPassWord">新密码</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult RestPassWord(int id, string newPassWord)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var result = ServiceFactory.SystemUserServiceInstance.Load(id);
            if (result != null)
            {
                result.Password = CommonMethod.JiaMi(newPassWord);
                responseResult.Success = ServiceFactory.SystemUserServiceInstance.UpdateEntities(result);
            }
            else
            {
                responseResult.Message = "找不到该用户";
            }
            return Json(new
            {
                success = responseResult.Success,
                message = responseResult.Message
            });
        }
        public ActionResult ModifyPassword(int id)
        {
            var systemUser = ServiceFactory.SystemUserServiceInstance.Load(id);
            var model = new SystemUserModel();
            if (systemUser != null)
            {
                model.UserAccount = systemUser.UserAccount;
            }
            return View(model);
        }
        [HttpPost]
        public ActionResult ModifyPassword(SystemUserModel model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = OpreateType.Update
            };
            var systemUser = ServiceFactory.SystemUserServiceInstance.Load(model.ID);
            if (systemUser == null)
                responseResult.Message = "无法找到该用户信息";
            else
            {
                if (systemUser.Password != CommonMethod.JiaMi(model.Password))
                {
                    responseResult.Message = "原密码错误";
                }
                else if (model.NewPassword != model.ConfirmPassword)
                {
                    responseResult.Message = "两次输入的密码不一致";
                }
                else
                {
                    systemUser.Password = CommonMethod.JiaMi(model.NewPassword);
                    responseResult.Success = ServiceFactory.SystemUserServiceInstance.UpdateEntities(systemUser);
                }
            }
            TempData["ResponseResult"] = responseResult;
            return RedirectToAction("ModifyPassword", new { id = model.ID });
        }
        #endregion

        public ActionResult SystemUserToRoleMapping(long userId)
        {
            var result = ServiceFactory.RoleToSystemUserServiceInstance.LoadEntities(p => p.UserID == userId).ToList();
            return View(result);
        }

        /// <summary>
        /// 设置用户角色
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveRoleToSystemUserMapping(RoleToSystemUser model, List<int> roleID)
        {
            var count = 0;
            var deleteCount = 0;
            if (model.UserID > 0)
            {
                if (roleID != null && roleID.Any())
                {
                    count += (from roleId in roleID
                              select new RoleToSystemUser
                              {
                                  UserID = model.UserID,
                                  RoleID = roleId
                              }
                                  into pageToAction
                                  let isExsitEntity = ServiceFactory.RoleToSystemUserServiceInstance.LoadEntities(p => p.RoleID == pageToAction.RoleID && p.UserID == pageToAction.UserID).FirstOrDefault()
                                  where isExsitEntity == null
                                  select pageToAction).Count(pageToAction => ServiceFactory.RoleToSystemUserServiceInstance.AddEntities(pageToAction).ID > 0);

                    //获取用户的之前的角色ID，且不包含这次的角色列表ID
                    var deleteRoleToAdminList = ServiceFactory.RoleToSystemUserServiceInstance.LoadEntities(p => p.UserID == model.UserID && !roleID.Contains(p.RoleID));
                    //删除掉
                    deleteCount += deleteRoleToAdminList.ToList().Sum(deleteRoleToPageToAction => ServiceFactory.RoleToSystemUserServiceInstance.DeleteEntities(deleteRoleToPageToAction) ? 1 : 0);
                }
            }
            CacheHelper.Instance.RemoveAllCache();
            var responseResult = new ResponseResult
            {
                Success = true,
                Message = string.Format("添加{0},移除{1}", count, deleteCount)
            };
            TempData["responseResult"] = responseResult;
            return RedirectToAction("SystemUserToRoleMapping", new { UserID = model.UserID });
        }
    }
}
